using System.Reflection;
using Agatha.Common;
using Agatha.Common.InversionOfControl;
using AutoMapper;
using Source.Common;
using System.Linq;

namespace EntityFramework.ServiceLayer
{
    public static class ComponentRegistration
    {
        public static void Register()
        {
            IoC.Container.Register(typeof(IUnitOfWork), typeof(UnitOfWork), Lifestyle.Transient);
            IoC.Container.Register(typeof(IObjectContextProvider), typeof(ObjectContextProvider), Lifestyle.Transient);
            IoC.Container.Register(typeof(IActiveObjectContextManager), typeof(ActiveObjectContextManager), Lifestyle.Transient);
            RegisterRepositories(Assembly.GetExecutingAssembly());
            RegisterMappers();
        }

        private static void RegisterMappers()
        {
            Mapper.CreateMap<Projects, ProjectInfo>();
        }

        private static void RegisterRepositories(Assembly assembly)
        {
            var repositoryInterfaceType = typeof(IRepository);

            foreach (var type in assembly.GetTypes())
            {
                var implementedInterfaces = type.GetInterfaces();

                if (!type.IsInterface && !type.IsGenericType && 
                    implementedInterfaces.Contains(repositoryInterfaceType))
                {
                    IoC.Container.Register(implementedInterfaces[1], type,Lifestyle.Transient);
                }
            }
        }

    }
}